#!BPY
# encoding: utf-8

"""
Name: 'KISS CM3D camera motion (.bin)'
Blender: 249
Group: 'Import'
Tooltip: 'CM3D camera motion importer'
"""

__author__ = 'Desuwa'
__version__ = '0.1'
__url__ = "http://code.google.com/p/anz2blend/"
__email__ = "desuwane@gmail.com"

"""
The MIT License

Copyright (c) 2011 Desuwa

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

import Blender
import bpy
from Blender import BGL
from Blender.BGL import *
from struct import unpack

#----------------
# BinaryReader
#----------------

def readSingle(r):
	data = r.read(4)
	return float(unpack("<f", data)[0]) if data != "" else False

def readInt(r):
	data = r.read(4)
	return int(unpack("<i", data)[0]) if data != "" else False

def readString(r):
	l = readInt(r)
	if l == "": return False
	data = r.read(l)
	return "".join(unpack("<%ds" % l, data)) if data != "" else False

#----------------
# GUI
#----------------
srcBin = Blender.Draw.Create("")
SCALEFACTOR = Blender.Draw.Create(10.0)

def getSrcBin(path):
	global srcBin
	srcBin.val = path
	Blender.Draw.Redraw(1)

def guiEvent(event, value):	
	if event == Blender.Draw.ESCKEY:
		Blender.Draw.Exit()
		return

def guiButton(event):
	global srcBin
	if event == 1:
		Blender.Window.FileSelector(getSrcBin, "Import")
	elif event == 666:
		if srcBin.val == "": return
		importCamera()
		Blender.Draw.Exit()
		Blender.Window.RedrawAll()
	elif event == 999:
		Blender.Draw.Exit()
	Blender.Draw.Redraw(-1)

def drawGui():
	global srcBin, SCALEFACTOR
	
	glClearColor(0.55, 0.57, 0.67, 1)
	glClear(BGL.GL_COLOR_BUFFER_BIT)
	
	glColor3f(0.70, 0.71, 0.85)
	glRasterPos2i(35, 40)
	Blender.Draw.Text("KISS Camera Importer " + __version__, "large")
	glRasterPos2i(35, 25)
	Blender.Draw.Text(__url__, "small")
	
	srcBin = Blender.Draw.String("BIN: ", 1, 35, 145, 315, 18, srcBin.val, 255)
	Blender.Draw.PushButton("Browse", 1, 355, 145, 55, 18, "")
	
	glColor3f(0.16, 0.168, 0.2)
	
	SCALEFACTOR = Blender.Draw.Number("Scale:", 3, 35, 115, 150, 18, SCALEFACTOR.val, 0, 100)
	glRasterPos2i(195, 120)
	Blender.Draw.Text("Scale the dimensions by 1 / SCALEFACTOR")
	
	Blender.Draw.PushButton("Import", 666, 35, 70, 75, 30, "")
	Blender.Draw.PushButton("Cancel", 999, 120, 70, 75, 30, "")

#----------------
# Main
#----------------
def importCamera():
	global srcBin, SCALEFACTOR
	
	srcBin = srcBin.val
	SCALEFACTOR = 1.0 if SCALEFACTOR.val == 0 else SCALEFACTOR.val
	
	if not Blender.sys.exists(srcBin):
		print "File doesn't exist: %s" % srcBin
		return
	
	print "======= Importing Camera ======="
	STARTTIME = Blender.sys.time()
	
	Blender.Window.WaitCursor(1)
	
	scn = bpy.data.scenes.active
	
	# camera data
	cam = Blender.Camera.New("persp", "CM3DCamera")
	cam.drawPassepartout = True
	cam.angle = 70
	"""
	fovipo = Blender.Ipo.New("Camera", "cameraFov")
	cam.ipo = fovipo
	fovipo.addCurve("Lens")
	"""
	# camera object
	camOb = scn.objects.new(cam, "CM3DCamera")
	camipo = Blender.Ipo.New("Object", "cameraMotion")
	camOb.ipo = camipo
	for c in ("LocX", "LocY", "LocZ"):
		camipo.addCurve(c)
	
	# tracker
	tracker = scn.objects.new("Empty", "CM3DTracker")
	trackeripo = Blender.Ipo.New("Object", "trackerMotion")
	tracker.ipo = trackeripo
	for c in ("LocX", "LocY", "LocZ"):
		trackeripo.addCurve(c)
		
	# adding constraint
	const = camOb.constraints.append(Blender.Constraint.Type.TRACKTO)
	const[Blender.Constraint.Settings.TARGET] = tracker
	const[Blender.Constraint.Settings.TRACK] = Blender.Constraint.Settings.TRACKNEGZ
	const[Blender.Constraint.Settings.UP] = Blender.Constraint.Settings.UPY
	
	with open(srcBin, "rb") as r:
		frameCount = readInt(r)
		r.read(12)
	
		scn.getRenderingContext().endFrame(frameCount)
	
		for frame in xrange(1, frameCount + 1):
			# camera loc X
			val = readSingle(r) / SCALEFACTOR
			bez = Blender.BezTriple.New([frame, val, 0])
			camipo[Blender.Ipo.OB_LOCX].append(bez)
			# camera loc Z
			val = readSingle(r) / SCALEFACTOR
			bez = Blender.BezTriple.New([frame, val, 0])
			camipo[Blender.Ipo.OB_LOCZ].append(bez)
			# camera loc Y
			val = readSingle(r) / SCALEFACTOR
			bez = Blender.BezTriple.New([frame, val, 0])
			camipo[Blender.Ipo.OB_LOCY].append(bez)
			
			""" Yeah, well, no...
			# camera lens
			val = readSingle(r) * 2
			bez = Blender.BezTriple.New([frame, val, 0])
			fovipo[Blender.Ipo.CA_LENS].append(bez)
			"""
			
			r.read(4)
			
			r.read(16)
			
			# tracker loc X
			val = readSingle(r) / SCALEFACTOR
			bez = Blender.BezTriple.New([frame, val, 0])
			trackeripo[Blender.Ipo.OB_LOCX].append(bez)
			# tracker loc Z
			val = readSingle(r) / SCALEFACTOR
			bez = Blender.BezTriple.New([frame, val, 0])
			trackeripo[Blender.Ipo.OB_LOCZ].append(bez)
			# tracker loc Y
			val = readSingle(r) / SCALEFACTOR
			bez = Blender.BezTriple.New([frame, val, 0])
			trackeripo[Blender.Ipo.OB_LOCY].append(bez)
			
			r.read(4)
			
	camOb.link(cam)
	scn.objects.active = None
	scn.objects.selected = []
	scn.update()
	Blender.Set('curframe', 1)
	Blender.Window.WaitCursor(0)
	print "== Done, took %f seconds ==" % (Blender.sys.time() - STARTTIME)

#----------------
# Here it comes
#----------------
Blender.Draw.Register(drawGui, guiEvent, guiButton)

